<template>
    <view class="wrapper">
        <view class="item_top">
            <view class="tit1">{{ buildingObj.buildingName }}</view>
            <view class="tit2">{{ buildingObj.buildingAddress }}</view>
        </view>
        <view class="item_row" v-for="(item, i) in buildingObj.list" :key="i" @click="showEdits(item)">
            <view class="row_left">{{ item.floorName }}</view>
            <view class="row_right">
                <view class="row_right_item1">{{ item.floorAllNum || '--' }}层</view>
                <view class="row_right_item2" v-if="item.eleIds"></view>
                <view class="row_right_item3" v-if="item.eleIds">{{ (item.eleIds || '').split(',').length }}梯</view>
                <view class="row_right_item4"><uni-icons color="#ccc" size="18" :type="'arrowright'" /></view>
            </view>
        </view>
        <view class="name_row_em" v-if="!buildingObj.list || buildingObj.list.length === 0" >
            <view>
                <image style="width: 64rpx;height: 64rpx;" src="/static/images/default.png"></image>
            </view>
            <view class="empty_tit">暂无电梯数据</view>
        </view>
        <view style="height: 100rpx;"></view>
        <view class="item_btn">
            <view class="btn_item" @click="addBuildings">添加楼栋</view>
        </view>

        <!-- 添加-楼栋 -->
        <uni-popup ref="addWork" :mask-click="true" type="bottom" @change="changeShowState">
            <view class="add_work_content">
                <view class="line"><text></text></view>
                <scroll-view scroll-y="true" style="height: 70vh; padding-top: 20rpx">
                    <view class="content">
                        <view class="title">添加楼栋</view>
                        <view class="content_item" style="margin-top: 32rpx; margin-bottom: 24rpx;">
                            <view class="name">楼栋号
                                <text class="reds">*</text>
                                <text class="tips">(提醒：只需录入楼栋号，梯号信息无需填写)</text>
                            </view>
                            <view class="select_item">
                                <uni-easyinput suffixIcon="arrowright" v-model="louFrom.floorName" placeholder="请选择楼栋结构"
                               ></uni-easyinput>
                                <view class="feid_item" @click="seleClick"></view>
                            </view>
                            
                            <div class="sele_item">
                                <uni-easyinput clearSize="16" :styles="{ height: '60rpx', width: '200rpx',widthS:'auto',flexS:'none' }" v-for="(it, i) in eleArr" :key="i"
                                    placeholder="请输入" v-model="it.val">
                                    <view slot="right" style="margin-right: 10rpx;" v-if="it.name !== '无后缀'">{{ it.name }}
                                    </view>
                                </uni-easyinput>
                            </div>
                        </view>
                        <view class="content_item">
                            <view class="name">楼层编号
                                <text class="tips">(提醒：楼层编号只可使用数字，英文字符)</text>
                            </view>
                            <!-- <uni-easyinput  @blur="changefloorNums" @clear="clearfloorNums" v-model="louFrom.floorNums"
                                placeholder="请输入楼层编号，或在下方快速配置"></uni-easyinput> -->
                            <view class="row-item">
                                <view class="col-item" v-for="(it, index) in cengList" :key="index">
                                        <uni-easyinput clearSize="16" :styles="{ width: '160rpx',widthS:'auto',flexS:'none' }" @blur="handlTableBlur(it, index)" @clear="clearfloorNums(it, index)" v-model.trim="it.floorNum"
                                placeholder="请输入"></uni-easyinput>
                                        <view class="del_cel_item" @click="delPhoneClick(it, index)">
                                            <image style="width: 32rpx;height: 32rpx;" src="/static/images/delete.png"></image>
                                        </view>
                                </view>
                                <view class="row_add_item">
                                    <view @click="addPhoneClick"><uni-icons color="#0091FF" size="18" :type="'plusempty'" />添加</view>
                                </view>
                            </view>

                            <view class="louceng">
                                <view class="louceng_left">
                                    <view class="louceng_left_item">起始楼层</view>
                                    <uni-easyinput clearSize="16" :styles="{ height: '60rpx' }" v-model="louFrom.floorBeginNum"
                                        placeholder="请输入起始楼层"></uni-easyinput>
                                </view>
                                <view class="louceng_cont">
                                    <view class="louceng_left_item">楼层数量</view>
                                    <uni-easyinput clearSize="16" :styles="{ height: '60rpx' }" v-model="louFrom.floorEndNum"
                                        placeholder="请输入楼层数量"></uni-easyinput>
                                </view>
                                <view class="louceng_right" @click="fastClick">
                                    <view class="louceng_right_item">快速配置</view>
                                    <view class="louceng_right_item">楼层编号</view>
                                </view>
                            </view>

                        </view>
                        <view class="content_item">
                            <view class="name">实际楼层数量</view>
                            <view class="">{{ cengList.length || louFrom.floorAllNum || '-' }}</view>
                        </view>
                        <view class="content_item">
                            <view class="name">电梯内呼图
                                <text class="tips">(提醒：请上传可达本楼各个楼层的电梯内呼图)</text>
                            </view>
                            <view class="name">
                                <image-drag-sort tips="上传图片" :max="3" @changeList="changeImgReason" :list="fileListExt">
                                </image-drag-sort>
                            </view>
                        </view>
                        <view class="content_item">
                            <view class="name">电梯数({{ selectedArr.length }})</view>
                            <view class="select_item">
                                <uni-easyinput suffixIcon="arrowright" v-model="value" placeholder="请选择电梯/搜索电梯关键词。如：3栋"
                               ></uni-easyinput>
                                <view class="feid_item" @click="eleClick"></view>
                            </view>
                            <view class="name_row" v-for="(it, i) in selectedArr" :key="i">
                                <view class="name_row_item1">{{ i + 1 }}</view>
                                <view class="name_row_item2" @click="toEleDetail(it)">{{ it.elevatorAddress }}</view>
                                <view class="name_row_item3" @click.stop="delSelected(it, i)">
                                    <image style="width: 32rpx;height: 32rpx;" src="/static/images/delete.png"></image>
                                </view>
                            </view>
                            <view class="name_row_empty" v-if="selectedArr.length === 0">
                                <view>
                                    <image style="width: 64rpx;height: 64rpx;" src="/static/images/default.png"></image>
                                </view>
                                <view class="empty_tit">暂无电梯数据</view>
                            </view>
                        </view>

                    </view>
                </scroll-view>
                <view class="save"><button hover-class="none" @click="handleSave">确定</button></view>
            </view>
        </uni-popup>
        <!-- 选择楼栋 -->
        <loudongCom ref="loudongCom" @bindClose="bindClose" :seleArr="seleArr" @selectChange="submitDate" />
        <!-- 选择电梯 -->
        <loudongSeleCom ref="loudongSeleCom" :seleShows="seleShows" @bindClose="closeSele" :selectedArr="selectedArr"
            :seleArrs="buildingData" @selectChecd="selectChecd" />
        <previewMedia ref="previewMedia"></previewMedia>

    </view>
</template>

<script>
import unipopup from '@/components/uni-popup/uni-popup';
import uniEasyinput from '../components/uni-easyinput/uni-easyinput';
import ImageDragSort from '@/components/image-drag-sort/index.vue';
import loudongCom from './components/loudongCom.vue';
import loudongSeleCom from './components/loudongSeleCom.vue';

import {
	getElevatorListLou,
	getElevatorTemplistLou,
	elevatorAddUpdata,
	getElevatorTempDetail
} from '@/apis/myElevator.js';
import {
	myMaintainBuildingChilds
} from '@/apis/barrierSearch.js';

export default {
	components: {
		unipopup,
		uniEasyinput,
		ImageDragSort,
		loudongCom,
		loudongSeleCom
	},
	data() {
		return {
			value: '',
			fileListExt: [],
			showState: false,
			seleArr: [],
			eleArr: [],
			louFrom: {
				buildingId: '',
				floorAllNum: '',
				floorAnotherName: '',
				floorBeginNum: '',
				floorEndNum: '',
				floorName: '',
				floorNums: '',
				jyImages: [],
				templateId: '',
				elevatorIds: '',
			},
			buildingData: [],
			buildingId: '',
			buildingObj: {},
			selectedArr: [],// 已选电梯
			seleShows: false,
			cengList:[],
		};
	},
	onLoad(e) {
		console.log(e, 'eeeeeeee');
		this.buildingId = e.buildingId;
		this.initGetList();
	},
	methods: {
		// 获取列表
		initGetList() {
			uni.showLoading({ title: '加载中' });
			getElevatorListLou({ buildingId: this.buildingId }).then(({ data }) => {
				uni.hideLoading();
				this.buildingObj = data || {};
			});
		},
		// 获取项目下电梯
		myMaintainBuildingChilds() {
			return new Promise((resolve, reject) => {
				myMaintainBuildingChilds({ buildingId: this.buildingId, current: 1, size: 200 }).then(({ data }) => {
					this.buildingData = (data.records || []).map(item => {
						return { ...item, acts: false };
					});

					resolve(data);
				});
			});
		},
		// 获取电梯模板
		getElevatorTemplist() {
			return new Promise((resolve, reject) => {
				getElevatorTemplistLou({ buildingId: this.buildingId }).then(({ data }) => {
					this.seleArr = data || [];
					resolve(data);
				});
			});
		},
		// 获取楼栋详情
		getElevatorTempDetail(id = '') {
			uni.showLoading({ title: '加载中' });
			return new Promise((resolve, reject) => {
				getElevatorTempDetail({ id }).then(({ data }) => {
					console.log(data, '获取楼栋详情');
					uni.hideLoading();
					resolve(data);
				});
			});
		},
		// 失去焦点
		handlTableBlur(row, i) {
			console.log('handlTableBlur', row, i);
			if (!row.floorNum) {
				// row.floorNum = ""
			} else {
				let res = /^[-a-zA-Z0-9]+$/;
				if (!res.test(row.floorNum)) {
					row.floorNum = '';
					uni.showToast({
						title: '请输入正确楼层编号',
						icon: 'none',
					});
				} 
			}
			this.$forceUpdate();
		},

		// 快速生成编号
		fastClick() {
			let res = /^-?\d+/;
			let res1 = /^\d+$/;
			if (!res.test(this.louFrom.floorBeginNum)) {
				uni.showToast({
					title: '请输入正确起始楼层',
					icon: 'none',
				});
				return;
			}
			if (!res1.test(this.louFrom.floorEndNum)) {
				uni.showToast({
					title: '请输入正确楼层数量',
					icon: 'none',
				});
				return;
			}
			if (Number(this.louFrom.floorBeginNum) > Number(this.louFrom.floorEndNum)) {
				uni.showToast({
					title: '起始楼层不能大于楼层数量',
					icon: 'none',
				});
				return;
			}
			if (Number(this.louFrom.floorEndNum) > 99) {
				uni.showToast({
					title: '楼层数量不能大于99',
					icon: 'none',
				});
				return;
			}
			if (this.louFrom.floorEndNum && this.louFrom.floorBeginNum) {
				let obj = this.getNumbersInRange(Number(this.louFrom.floorBeginNum), Number(this.louFrom.floorEndNum));
				if (obj.strNum) {
					this.louFrom.floorNums = obj.strNum;
					this.louFrom.floorAllNum = obj.strNum.split(',').length;
					this.cengList = obj.strNum.split(',').map((item, index) => {
						return {floorNum:item, id: '',numError:''};  
					});
				}
				if (this.louFrom.floorBeginNum < 0) {
					let arrs =  obj.strNum.split(',') || [];
					arrs.forEach((item, index) => {
						if (item === '0') {
							arrs.splice(index, 1);
						}
					});
					this.louFrom.floorNums = arrs.join(',');
					this.louFrom.floorAllNum = arrs.length;
					this.cengList = arrs.map((item, index) => {
						return {floorNum:item, id: '',numError:''};  
					});
				}
			}
		},
		// 快速生成编号
		getNumbersInRange(start, end) {
			const result = [];
			let count = start < 0 ? end + 1 : end;
			for (let i = 0; i < count; i++) {
				let num = start + i;
				result.push(num);
			}
			return { strNum: result.join(',') };
		},

		seleClick() {
			this.$refs.loudongCom.$refs.popups.open();
		},
		bindClose() {
			this.$refs.loudongCom.$refs.popups.close();
		},

		eleClick() {
			// this.$refs.loudongSeleCom.$refs.popupr.open()
			this.seleShows = true;
		},
		closeSele() {
			// this.$refs.loudongSeleCom.$refs.popupr.close()
			this.seleShows = false;
		},
		clearfloorNums() {
			this.louFrom.floorAllNum = '';
		},
		// 楼层编号
		changefloorNums(val) {
			console.log('changefloorNums', val, this.louFrom.floorNums, typeof (this.louFrom.floorNums));
			let res = /^[0-9a-zA-Z-]+(,[0-9a-zA-Z-]+)*$/;
			if (res.test(this.louFrom.floorNums)) {
				this.louFrom.floorAllNum = this.louFrom.floorNums.split(',').length;
			} else {
				this.louFrom.floorAllNum = '';
			}
		},
		// 添加
		addPhoneClick() {
			this.cengList.push({floorNum: '',id: '', numError:''});
		},
		// 删除
		delPhoneClick(obj, i) {
			this.cengList.splice(i, 1);
		},
		// 添加楼栋
		addBuildings() {
			this.$refs.addWork.open();
			this.getElevatorTemplist();
			this.myMaintainBuildingChilds();
		},
		// 选择图片
		changeImgReason(val) {
			this.fileListExt = val;
		},
		// 选择电梯
		selectChecd(arr) {
			this.selectedArr = arr.filter(item => item.acts);
		},
		delSelected(obj, i) {
			this.selectedArr.splice(i, 1);
		},
		// 选择楼栋模板
		submitDate(val) {
			if (val && val.length > 0) {
				this.eleArr = this.seleArr[val[0]].templates;
				this.louFrom.floorName = this.seleArr[val[0]].name;
			} else {
				this.eleArr = this.seleArr[0].templates;
				this.louFrom.floorName = this.seleArr[0].name;
			}
		},
		async showEdits(row) {
			this.getElevatorTemplist();
			await this.myMaintainBuildingChilds();
			let results = await this.getElevatorTempDetail(row.id);
			if (results) {
				this.louFrom = results;
				this.fileListExt = results.jyImages || [];
				this.louFrom.floorName = results.otherText;
				this.cengList = this.louFrom.numLists || [];
				this.eleArr = results.otherText.split('/').map((item, i) => {
					return {
						name: item,
						val: results.floorAnotherName.split('/')[i],
					};
				});
				this.selectedArr = [];
				results.elevatorIds.forEach(eleId => {
					this.buildingData.forEach(item => {
						if (item.id === eleId) {
							this.selectedArr.push(item);
						}
					});
				});
				this.$refs.addWork.open();
			}
		},

		handleSave() {
			let copyObj = Object.assign({}, this.louFrom);
			console.log(copyObj, this.louFrom, 'this.louFrom');
			if (!copyObj.floorName) {
				uni.showToast({ title: '请选择电梯位置', icon: 'none', });
				return;
			}
			let hasEleTotal = this.eleArr.some((item) => item.val);
			if (!hasEleTotal) {
				uni.showToast({ title: '请输入楼栋号', icon: 'none', });
				return;
			}

			if (!this.cengList.every(item=>item.floorNum)) {
				uni.showToast({ title: '请输入楼层编号', icon: 'none', });
				return;
			}
            
			copyObj.buildingId = this.buildingId;
			copyObj.jyImages = this.fileListExt;
			if (this.selectedArr && this.selectedArr.length > 0) {
				copyObj.elevatorIds = this.selectedArr.map(item => item.id);
			} else {
				copyObj.elevatorIds = [];
			}
			if (this.seleArr && this.seleArr.length > 0) {
				copyObj.templateId = (this.seleArr.find(item => item.name === copyObj.floorName) || {}).id;
			}
			if (this.eleArr && this.eleArr.length > 0) {
				copyObj.floorAnotherName = this.eleArr.map(item => item.val).join('/');
				copyObj.otherText = this.eleArr.map(item => item.name).join('/');
				copyObj.floorName = this.eleArr.filter(item => item.val).map(item => (item.val || '') + (item.name || '')).join('/').replaceAll('/', '').replaceAll('无后缀', '');
				this.eleArr.forEach(item => {
					if (item.val == '无后缀') {
						copyObj.floorName = '无后缀';
					}
				});
			}
			if (this.cengList && this.cengList.length > 0) {
				copyObj.floorAllNum = this.cengList.length;
				copyObj.numLists = this.cengList;
				copyObj.floorNums = this.cengList.map(item => item.floorNum).join(',');
			}
			console.log('submitTenantssss', copyObj);
			// return
			elevatorAddUpdata(copyObj).then(({ data }) => {
				console.log(data, 'data');
				this.$refs.addWork.close();
				this.initGetList();
				uni.$emit('buildingEditSuccess',{buildingId:this.buildingId});
			});
		},
		changeShowState(e) {
			if (!e.show) {
				this.eleArr = [];
				this.fileListExt = [];
				this.buildingData = [];
				this.selectedArr = [];
				this.cengList = [];
				this.louFrom = {
					buildingId: '',
					floorAllNum: '',
					floorAnotherName: '',
					floorBeginNum: '',
					floorEndNum: '',
					floorName: '',
					floorNums: '',
					jyImages: [],
					templateId: '',
					elevatorIds: '',
				};
			}
		},
		toEleDetail(item) {
			uni.navigateTo({
				url: `/subpages/elevator/projectInfo/eleDetail?id=${item.id}&type=` + 3
			});  
		}
	}
};
</script>
<style>
page {
    background: #F3F6F8;
}
</style>
<style lang="scss" scoped>
// /deep/.uni-easyinput__content-input{
//     height: 180rpx;
// }
// /deep/ .uni-easyinput{
//     flex: none;
//     width: 0;
// } 
.wrapper {

    .name_row_em {
        display: flex;
        align-items: center;
        flex-direction: column;
        justify-content: center;
        height: 200rpx;
        font-size: 26rpx;
        color: #999999;
    }
    .item_top {
        padding: 32rpx 40rpx 20rpx 40rpx;

        .tit1 {
            font-size: 42rpx;
            color: #333;
            font-weight: 600;
        }

        .tit2 {
            font-size: 24rpx;
            color: #999999;
        }
    }
    .row-item {
        display: flex;
        flex-wrap: wrap;
        row-gap: 24rpx;
        column-gap:28rpx;
        margin: 0 0 16px 0;
        .col-item{
            display: flex;
            height: 60rpx;
        }
        .del_cel_item{
            display: flex;
            align-items: center;
            margin-left: 10rpx;
        }
        .row_add_item{
            color: #0091FF;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }

    .item_row {
        background: #FFFFFF;
        border-radius: 4px;
        padding: 26rpx 16rpx;
        display: flex;
        align-items: center;
        margin: 0px 16rpx 20rpx 16rpx;

        .row_left {
            flex: 1;

        }

        .row_right {
            width: 186rpx;
            display: flex;
            align-items: center;
            font-size: 28rpx;
            color: #333333;
            justify-content: flex-end;

            .row_right_item2 {
                margin: 0 16rpx;
                width: 2rpx;
                height: 30rpx;
                background: #D8D8D8;
            }
        }
    }
}

.item_btn {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 200;
    background-color: #fff;
    height: 100rpx;
    line-height: 100rpx;
    width: 100%;
    display: flex;
    border-top: 2rpx solid #eeeeee;
    box-sizing: border-box;
    padding: 0 20rpx;
    display: flex;
    align-items: center;

    .btn_item {
        background: #0091ff;
        color: #fff;
        font-size: 26rpx;
        border-radius: 8rpx;
        width: 710rpx;
        height: 70rpx;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}

.add_work_content {
    background: #ffffff;
    border-radius: 8rpx;
    box-sizing: border-box;
    box-shadow: 0px 0px 8rpx 0px rgba(0, 0, 0, 0.2);
    height: 80vh;
    padding: 20rpx 0;

    .line {
        display: flex;
        justify-content: center;

        text {
            width: 64rpx;
            height: 10rpx;
            background: #d8d8d8;
            border-radius: 6rpx;
        }
    }

    .content {
        padding: 0 40rpx;
        padding-bottom: 20rpx;

        .title {
            // border-left: 4rpx solid #0091ff;
            // margin-left: -40rpx;
            // padding-left: 20rpx;
            margin-bottom: 20rpx;
            font-weight: bold;
            color: #333;
            font-size: 32rpx;
        }
    }

    .content_item {
        margin-bottom: 16rpx;

        .name {
            font-size: 26rpx;
            margin-bottom: 8rpx;
            font-weight: bold;
            color: #333;
            // border-left: 4rpx solid #0091ff;
            // padding-left: 10rpx;

            .reds {
                color: #e54b4b;
            }

            .tips {
                font-size: 24rpx;
                font-weight: normal;
                color: #FF7505;
            }
        }

        .reasonContent {
            display: flex;
            flex-wrap: wrap;

            view {
                width: 30%;
                height: 48rpx;
                margin-bottom: 20rpx;
                display: flex;
                justify-content: center;
                align-items: center;
                border: 2rpx solid #cccccc;
                border-radius: 8rpx;
                margin-right: 18rpx;
            }

            .active {
                color: #0091ff;
                border-color: #0091ff;
            }
        }

        .louceng {
            display: flex;
            justify-content: space-between;
            font-size: 24rpx;
            color: #666666;
            margin-top: 20rpx;

            .louceng_left {
                flex: 1;
            }

            .louceng_cont {
                flex: 1;
                margin: 0 20rpx;
            }

            .louceng_right {
                margin-top: 34rpx;
                flex: 1;
                display: flex;
                align-items: center;
                justify-content: center;
                flex-direction: column;
                border-radius: 4px;
                border: 1px solid #0091FF;
                height: 56rpx;
                width: 170rpx;
                color: #0091FF;
                line-height: 1.1;

            }
        }

        .name_row {
            display: flex;
            align-items: center;
            // margin-top: 20rpx;
            border-bottom: 2rpx#E9E9E9 solid;
            padding: 26rpx 0;
            font-size: 26rpx;
            .name_row_item1 {
                width: 50rpx;
               
                color: #333333;
            }

            .name_row_item2 {
                flex: 1;
                color: #333333;
            }

            .name_row_item3 {
                width: 70rpx;
                color: #333333;
                display: flex;
                align-items: center;
                justify-content: flex-end;
            }
        }
        
        .select_item{
            position: relative;
            margin-bottom: 16rpx;
            .feid_item{
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 70rpx;
                background: transparent;
                z-index: 99;

            }
        }

        .sele_item {
            display: flex;
            flex-wrap: wrap;
            margin-top: 20rpx;
            row-gap: 10rpx;
            column-gap: 10rpx;
        }
    }
    .name_row_empty {
            display: flex;
            align-items: center;
            flex-direction: column;
            justify-content: center;
            height: 200rpx;
            font-size: 26rpx;
            color: #999999;
        }

    .save {
        display: flex;
        justify-content: center;
        height: 100rpx;
        border-top: 2rpx solid #eee;
        line-height: 100rpx;
        align-items: center;

        button {
            display: flex;
            width: 670rpx;
            height: 70rpx;
            border-radius: 8rpx;
            justify-content: center;
            align-items: center;
        }
    }

}</style>